﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geoprocessor;
using System.Windows.Forms;
using hzGis.model;
using hzGis.utils;

namespace hzGis.service.impl
{
   public class YdhyService:IYdhyService
    {
       private FileService fileService;
       private List<Dictionary<string, string>> tDataPaths;
       private IFeatureClass input, overlay;
       private string gdbPath;
       private IWorkspace gdbWp;
       private string startTime;
       private string result;
       private int num = 2;
       public YdhyService()
       {
           fileService = new FileService();
       }
       public string ydhy(List<Dictionary<string, string>> dataPaths, string dir)
        {
            /**tDataPaths = dataPaths;
            input = fileService.openFeatureClassByShp(dataPaths[0]);
            overlay = fileService.openFeatureClassByShp(dataPaths[1]);
            result = dir+"\\result.shp";
            List<IFeatureClass> datas = new List<IFeatureClass>() { input, overlay };
            IntersectFeatureClass(datas, result, gpToolExecuted);**/
            return "";
        }


        public void gpToolExecuted(object sender, ToolExecutedEventArgs e)
        {
            if (num < tDataPaths.Count - 1)
            {
                IFeatureWorkspace fw = gdbWp as IFeatureWorkspace;
                input = fw.OpenFeatureClass(result);
                num = num + 1;
                Dictionary<string, string> tDataPath = tDataPaths[num];
                string path = tDataPaths[num]["path"];
                if (path.IndexOf("&") > -1)
                {
                    string[] pathArray = path.Split('&');
                    overlay = fw.OpenFeatureClass(pathArray[1]);
                }
                else
                {
                    FeatureClassInfo featureClassInfo = FeatureClassUtils.openShpFile(path);
                    overlay = featureClassInfo.fc;
                }
                List<IFeatureClass> datas = new List<IFeatureClass>() { input, overlay };
                result = "tbl" + tDataPaths[num - 1]["year"] + tDataPaths[num]["year"];
                IntersectFeatureClass(datas, gdbPath + "\\" + result, gpToolExecuted);
            }
            else
            {
                string endTime = System.DateTime.Now.ToString("F");
                MessageBox.Show("用地还原从" + startTime + "到" + endTime);
            }
            
        }

        private IFeatureClass Intersect(IFeatureClass pSourceFeatureClass, IFeatureClass pTargetFeatureClass, string filePath)
        {
            ITable pSourceTable = pSourceFeatureClass as ITable;
            ITable pTargetTable = pTargetFeatureClass as ITable;
            // IWorkspaceName
            IWorkspaceName pWorkspaceName = new WorkspaceName() as IWorkspaceName;
            pWorkspaceName.WorkspaceFactoryProgID = "esriDataSourcesGDB.ShapefileWorkspaceFactory";
            pWorkspaceName.PathName = System.IO.Path.GetDirectoryName(filePath);
            // IFeatureClassName
            IFeatureClassName pFeatureClassName = new FeatureClassName() as IFeatureClassName;
            pFeatureClassName.ShapeFieldName = "Shape";
            pFeatureClassName.ShapeType = esriGeometryType.esriGeometryPolygon;
            pFeatureClassName.FeatureType = esriFeatureType.esriFTSimple;
            // IDatasetName
            IDatasetName pDatasetName = pFeatureClassName as IDatasetName;
            pDatasetName.WorkspaceName = pWorkspaceName;
            pDatasetName.Name = System.IO.Path.GetFileNameWithoutExtension(filePath);
            // 计算相交部分
            IBasicGeoprocessor pBasicGeoprocessor = new BasicGeoprocessor();
            IFeatureClass pFeatureClass = pBasicGeoprocessor.Intersect(pSourceTable, false, pTargetTable, false, 0.001, pFeatureClassName);
            return pFeatureClass;

        }

        /// <summary>
        /// 执行GP工具
        /// </summary>
        /// <param name="gpProcess"></param>
        /// <returns></returns>
        private void ExecuteGPTool(IGPProcess gpProcess, System.EventHandler<ToolExecutedEventArgs> gpToolExecuted)
        {
            Geoprocessor GP = new Geoprocessor();
            GP.OverwriteOutput = true;
            GP.ToolExecuted += new EventHandler<ESRI.ArcGIS.Geoprocessor.ToolExecutedEventArgs>(gpToolExecuted);
            GP.LogHistory = true;
            GP.ClearMessages();
            try
            {
                GP.Execute(gpProcess, null);
            }
            catch (Exception)
            {
                object sev = null;
                MessageBox.Show(GP.GetMessages(ref sev));
            }
        }

        /// <summary>
        /// 相交要素
        /// </summary>
        /// <param name="pLayers">相交图层列表</param>
        /// <param name="path">输出路径</param>
        /// <returns></returns>
        public void IntersectFeatureClass(List<IFeatureClass> featureClasss, string path, System.EventHandler<ToolExecutedEventArgs> gpToolExecuted)
        {
            //对要素类进行相交运算
            IGpValueTableObject gpValueTableObject = new GpValueTableObject();
            gpValueTableObject.SetColumns(featureClasss.Count);
            for (int i = 0; i < featureClasss.Count; i++)
            {
                IFeatureClass pFeatureClass = featureClasss[i];
                object Row = pFeatureClass;
                gpValueTableObject.AddRow(ref Row);
            }
            //相交工具
            ESRI.ArcGIS.AnalysisTools.Intersect IntersectTool = new ESRI.ArcGIS.AnalysisTools.Intersect();
            IntersectTool.in_features = gpValueTableObject;
            IntersectTool.out_feature_class = path;
            //执行GP工具
            ExecuteGPTool(IntersectTool, gpToolExecuted);
        }

        public void ydhyPro(List<Dictionary<string, string>> paths, IWorkspace tgdbWp, string path, string tstartTime)
        {
            tDataPaths = paths;
            gdbWp = tgdbWp;
            gdbPath = path;
            startTime = tstartTime;
            IFeatureWorkspace fw = gdbWp as IFeatureWorkspace;
            string tbllast = paths[0]["path"];
            string tbllast_1 = paths[1]["path"];
            string[] tbllasts = tbllast.Split('&');
            string[] tbllast_1s = tbllast_1.Split('&');
            input = fw.OpenFeatureClass(tbllasts[1]);
            overlay = fw.OpenFeatureClass(tbllast_1s[1]);
            List<IFeatureClass> datas = new List<IFeatureClass>() { input, overlay };
            result = "tbl" + paths[0]["year"] + paths[1]["year"];
            IntersectFeatureClass(datas, path +"\\" + result, gpToolExecuted);

        }

    }
}
